package com.xiebishe.mylibrary.common.pageStatus.topHandler;

import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;

/**
 * 通过向layout的父view添加loading等状态view 达到状态替换的效果 用于初始化后便不能添加view的layout（SmartRefreshLayout），和其他没有实现的layout
 *
 * @param <VIEW>
 * @author wangwenbo
 */
public class AddRemoveInParentTopStatusHandler<VIEW extends ViewGroup> extends TopStatusHandler<VIEW> {

    public AddRemoveInParentTopStatusHandler(@NonNull VIEW layout, int centerInTopPx) {
        super(layout, centerInTopPx);
    }

    private FrameLayout frameLayout;
    private ViewGroup parent;


    @Override
    protected void removeView(@NonNull View view, @NonNull VIEW layout) {
        parent.removeView(frameLayout);
        frameLayout.removeView(view);
    }

    @Override
    protected boolean onHideContent(@NonNull VIEW layout) {
        layout.setVisibility(View.INVISIBLE);
        return true;
    }

    @Override
    protected boolean onShowContent(@NonNull VIEW layout) {
        layout.setVisibility(View.VISIBLE);
        return true;
    }

    @Override
    protected void addToTop(@NonNull View view, @NonNull VIEW layout, int centerInTopPx) {
        parent = (ViewGroup) layout.getParent();
        if (parent instanceof ViewPager || parent instanceof AdapterView || parent instanceof RecyclerView || parent instanceof SmartRefreshLayout) {
            throw new IllegalArgumentException("AddRemoveInParentStatusHandler 不能在parent为 " + parent.getClass().getSimpleName() + "中使用");
        }
        if (frameLayout == null) {
            frameLayout = new FrameLayout(view.getContext());
        }
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, centerInTopPx);
        layoutParams.gravity = Gravity.TOP;
        frameLayout.addView(view, layoutParams);
        parent.addView(frameLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    }
}
